import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';

// 路由守卫组件
const AuthGuard = ({ children, requiresAuth }) => {
  const location = useLocation();
  const isAuthenticated = localStorage.getItem('token'); // 假设使用token判断是否登录
  
  // 如果路由需要认证但用户未登录，重定向到登录页
  if (requiresAuth && !isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  
  // 如果用户已登录且访问登录页，重定向到首页
  if (isAuthenticated && location.pathname === '/login') {
    return <Navigate to="/dashboard" replace />;
  }
  
  return children;
};

export default AuthGuard;